import os
from git import Repo, InvalidGitRepositoryError

def get_repo_diff(repo_path, commit_a, commit_b, output_dir):
    try:
        # 初始化仓库对象
        repo = Repo(repo_path)
        if not repo.bare:
            # 获取 diff
            diff = repo.git.diff(commit_a, commit_b)
            # print(f"Generating diff for {repo_path} between {commit_a} and {commit_b}...")
            # print(diff)
            
            # 创建输出目录（如果不存在）
            os.makedirs(output_dir, exist_ok=True)
            
            # 生成 diff 文件名
            diff_file_name = f"{repo_path.split('/')[-1]}_{commit_a[:8]}_{commit_b[:8]}.diff"
            diff_file_path = os.path.join(output_dir, diff_file_name)
            
            # 将 diff 写入文件
            with open(diff_file_path, 'w') as f:
                f.write(diff)
            
            print(f"Diff for {repo_path} saved to {diff_file_path}")
        else:
            print(f"Repository at {repo_path} is bare, no diff available.")
    except InvalidGitRepositoryError:
        print(f"{repo_path} is not a valid Git repository.")
    except Exception as e:
        print(f"An error occurred while processing {repo_path}: {e}")

def main():
    # 定义仓库路径列表
    repo_paths = [
        ['/home/ubuntu/sonic-buildimage/.source/src/sonic-utilities'
         , '6245f0b38da6838f0bf0b2b7820b0abf99ea6e0e', '269164408d04fbd751389b2808972665be09534e'],
        ['/home/ubuntu/sonic-buildimage/.source/src/sonic-swss'
         , '7116be00d4862d7431be046c1bf7cd251e86273a', '897b46cdb8d11392631fbd0fa7e248454e432260'],
        ['/home/ubuntu/sonic-buildimage/.source/src/sonic-utilities'
         , 'a904cfbad396666c8ae87da2cbce57a8505ccbfc', '140a706ffe47fe2313a8d17afcf88788c8158973']
    ]
    
    # 定义输出目录
    output_directory = './diff_outputs'
    
    # 遍历每个仓库并获取 diff
    for repo_path, commit_a, commit_b in repo_paths:
        get_repo_diff(repo_path, commit_a, commit_b, output_directory)

if __name__ == "__main__":
    main()